package com.ebways.rpc.provider;

import com.ebways.rpc.service.User;
import com.ebways.rpc.service.UserService;
import com.ebways.rpc.service.UserService2;
import com.ebways.rpc.service.impl.UserService2Impl;
import com.ebways.rpc.service.impl.UserServiceImpl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by gmq on 2017/08/29.
 *
 * @version 1.0
 * @since 2017/08/29 11:07
 */
public class RpcProvider {

    public static void main(String[] args) {

        try {
            // 写一个socket服务端，用于接收订单系统发送过来的请求
            ServerSocket serverSocket = new ServerSocket(6666);
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//                    int id = ois.read();
//                    System.out.println("接收到订单系统发送的id= " + id);


                    // 调用获取用户信息的业务逻辑

                    // 反射：4个条件： 类的名称（包名+类名），方法的名称，入参参数的类型，入参参数的值
                    String className = ois.readUTF();
                    String methodName = ois.readUTF();
                    Class[] parameteTypes = (Class[]) ois.readObject();
                    Object[] argss = (Object[]) ois.readObject();

                    Class clazz = getClass(className);

                    Method method = clazz.getMethod(methodName, parameteTypes);
                    Object result = method.invoke(clazz.newInstance(), argss);

                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(result);
                    oos.flush();

                    oos.close();
                    ois.close();
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 暴露服务：找到规则，通过配置或者其他方式
     * TODO: 需要改进
     * 注册接口服务
     *
     * @param interfaceName
     * @return
     */
    public static Class getClass(String interfaceName) {
        // 注册接口服务
        Class clazz = null;
        if (interfaceName.equals(UserService.class.getName())) {
            clazz = UserServiceImpl.class;
        } else if (interfaceName.equals(UserService2.class.getName())) {
            clazz = UserService2Impl.class;
        }

        return clazz;
    }
}
